Computers & Society,
Data & Numbers & Algorithms

Chapters 4, 5 & 6 โ€” complete notes with definitions, analogies, memory tricks, interactive tools, flashcards and a quiz covering all past-paper topics.

๐ŸŒ Chapter 4 โ€” Computers & Society

Turing machines, AI, ethics, environment, the Internet & emerging tech. On every paper!

4

๐Ÿค– The Turing Machine & Foundations of Computing

A Turing Machine is a theoretical computing device proposed by Alan Turing in 1936. It has: an infinite tape divided into cells, a read/write head, a finite set of states, and a transition table. By reading symbols and changing state, it can compute anything computable. It is the mathematical model behind every modern computer.

A Turing Machine is like a very simple post-office worker on an infinitely long conveyor belt. They read the next package (cell), follow a rulebook (transition table), write on it, and move left or right. Simple rules, infinite power!

Turing-complete โ€” any system or programming language capable of simulating a Turing machine, meaning it can carry out any computation given enough time and memory. Python, Java, C are all Turing-complete. (DEB 2023 asked this directly.)

Tracing a Turing Machine โ€” State Transition Table

The 2022 exam had you trace a Turing machine. The table shows: Current State + Symbol Read โ†’ Write Symbol, then move Right (R) or Left (L), then new State.

Example: Tape starts as 0 1 1 0 B (B = blank), head starts at position 0, state S0. Transition rule: if S0 reads 0 โ†’ write 1, move R, stay S0; if S0 reads 1 โ†’ write 0, move R, stay S0; if S0 reads B โ†’ HALT.

This machine flips every bit!

State: S0 | Head at position 0

Turing Machine = Tape + Head + States + Transitions = "THST" โ†’ "The Hard Stuff Today" ๐Ÿ˜„

2022 paper: trace a 4-state Turing machine step by step. Fill in: the current state, the symbol on the tape at the head, what gets written, which direction the head moves, and the new state. Go slowly, one step at a time!

History of Computers โ€” The Generations

GenerationTechnologyEraKey milestone
1stVacuum tubes1940sENIAC (1945) โ€” first electronic general-purpose computer
2ndTransistors1950sSmaller, cheaper, more reliable than vacuum tubes
3rdIntegrated circuits1960sJack Kilby โ€” multiple transistors on one chip
4thMicroprocessors1970s+Intel 4004 โ€” entire CPU on a single chip
5thAI & Ubiquitous computingTodayMachine learning, mobile, IoT, quantum

Key figures to know: Charles Babbage (Analytical Engine โ€” first design for a programmable computer), Ada Lovelace (world's first programmer), Alan Turing (theoretical CS + WWII code-breaking), John von Neumann (stored-program concept), Tim Berners-Lee (invented the World Wide Web, 1989), Tony Hoare (invented Quicksort, 1960).

๐Ÿค– Artificial Intelligence & Machine Learning

AI has appeared on EVERY paper since 2022. Memorise these definitions exactly.

Artificial Intelligence (AI) โ€” the branch of computer science concerned with building machines or programs that can perform tasks that would normally require human intelligence โ€” such as recognising speech, making decisions, learning from experience, and solving problems.

๐ŸŽฏ
Narrow AI
Designed for ONE specific task. All AI today is narrow AI. Examples: Siri, spam filters, chess engines, recommendation algorithms, face recognition.
๐ŸŒ
AGI (General AI)
Hypothetical AI with human-level reasoning across EVERY domain. Does not yet exist. Would be able to learn any task a human can. (2024 paper.)
๐Ÿ“ˆ
Generative AI
Creates NEW content (text, images, audio, video, code) based on patterns learned from training data. Examples: ChatGPT, Gemini, DALL-E, Midjourney. (2024 paper.)
๐Ÿ‘๏ธ
Computer Vision
AI that analyses, identifies and understands objects/faces in images or video. Confidence scores = how sure the model is. Used in medical imaging, self-driving cars, security.

Machine Learning โ€” 3 Types

Machine Learning โ€” a subset of AI in which systems learn from data and improve over time without being explicitly programmed for every case.

Traditional programming: tell the computer exactly what to do for every situation. Machine Learning: show it thousands of examples and let it figure out the rules itself โ€” like training a dog with treats rather than writing out every command!

๐Ÿ‘ฉโ€๐Ÿซ Supervised Learning
Trained on labelled data โ€” you tell it the right answer for each example.
Spam filter (labelled as spam/not spam), image classifier (labelled cat/dog).
๐Ÿ” Unsupervised Learning
Finds hidden patterns or clusters in unlabelled data.
Customer segmentation, anomaly detection, recommendation systems finding similar users.
๐ŸŽฎ Reinforcement Learning
Learns from rewards and punishments โ€” trial and error to maximise a score.
Game-playing AI (chess, Go, video games), robot navigation, autonomous driving.

S-U-R = Supervised (teacher gives answers), Unsupervised (no labels, finds patterns), Reinforcement (learns from rewards). "Students Usually Reward good learning!"

Bias in Machine Learning

Bias in ML occurs when a model's predictions systematically favour or disadvantage certain groups โ€” usually because the training data was unrepresentative.

How to reduce bias: use diverse, balanced training data; audit models for fairness; include diverse teams in design; test across different demographics; use bias-detection tools.

2025 paper: State a benefit AND a limitation of AI in medical diagnosis. Benefit: faster/more consistent screening, detects patterns humans miss. Limitation: biased if trained on narrow demographics; "black box" lack of explainability; liability issues.

Is it Machine Learning? Spot the difference!

ScenarioML or not?Why
Netflix recommends shows based on your viewing historyโœ… YESLearns from data over time, improves recommendations
Robotic lawnmower with fixed sensor rulesโŒ NOHard-coded rules, no learning from data
Spam filter that updates as new spam patterns emergeโœ… YESImproves performance from new examples
Calculator performing maths operationsโŒ NOFollows fixed formulas, no learning

๐ŸŒ The Internet vs The World Wide Web

The Internet is the global network of interconnected computer networks โ€” it is the hardware infrastructure (cables, routers, servers).

The Internet carries: email, FTP, video calls, online gaming, the Web, and more.

The World Wide Web (WWW) is a service that runs on the Internet โ€” an interconnected collection of websites and pages accessed via HTTP/HTTPS using browsers.

The Web is just ONE application that uses the Internet.

The Internet is like the road network โ€” the physical infrastructure. The World Wide Web is like Google Maps โ€” a service that uses those roads. You can also drive to a friends house (email) on the same roads without using Maps!

Internet = Infrastructure (the roads). Web = One service on those roads. "Internet is Infrastructure. Web is one Way to use it."

TermWhat it isExample
HTTPHyperText Transfer Protocol โ€” rules for browsers requesting web pages from servershttp://example.com
HTTPSSecure HTTP โ€” encrypted with TLS/SSL. Protects data in transit.https://mybank.ie
URLUniform Resource Locator โ€” the unique address of a resource on the webhttps://example.com/page
Web BrowserSoftware to access and display web pagesChrome, Firefox, Safari, Edge
Search EngineWebsite/service that indexes the web and returns results for queriesGoogle, Bing, DuckDuckGo

DEB 2024 asked you to distinguish a web browser from a search engine. Browser = software to VIEW pages. Search engine = website/service to FIND pages. You use the browser to access the search engine!

โš–๏ธ Ethics, Environment & Society

Ethical Issues in Computing

Ethical IssueDescription
Privacy & surveillanceConstant data collection, location tracking, facial recognition by governments/companies
Algorithmic biasAI systems unfairly disadvantaging certain groups due to biased training data
Intellectual propertyCopyright, piracy, AI-generated content stealing original work
Digital divideUnequal access to technology between rich/poor, urban/rural populations
DeepfakesAI-generated fake videos/images used to spread misinformation or harm individuals
Automation & jobsRobots and AI replacing human workers, causing unemployment
Data ownershipWho owns your personal data โ€” you or the company that collects it?

GDPR โ€” General Data Protection Regulation

GDPR (2018) is EU law that regulates how organisations collect, store, and use personal data. It gives individuals control over their own data.

Your Rights Under GDPRWhat it means
Right of AccessYou can request a copy of all data held about you
Right to RectificationYou can correct inaccurate data
Right to Erasure"Right to be forgotten" โ€” request deletion of your data
Right to PortabilityTransfer your data to another service
Right to ObjectObject to your data being used for certain purposes

GDPR rights: A-R-E-P-O = Access, Rectification, Erasure, Portability, Object. "Are Regulations Ever Properly Obeyed?" ๐Ÿ˜„

Environmental Impact of Computing

โš ๏ธ Problems

  • E-waste โ€” discarded electronics with toxic materials
  • Data centre energy โ€” huge electricity consumption (often coal-powered)
  • AI training โ€” massive carbon footprint (training GPT-4 โ‰ˆ 500 tonnes COโ‚‚)
  • Rare-earth mining โ€” destructive extraction for lithium, cobalt, etc.
  • Streaming โ€” video streaming = 1% of global electricity use

โœ… Solutions

  • Renewable energy for data centres (Google, Microsoft)
  • Efficient algorithms โ€” less computation = less energy
  • Longer device lifecycles โ€” repair instead of replace
  • E-waste recycling programmes
  • Optimised cooling for data centres

Cloud Computing โ€” Pros & Cons

โœ… AdvantagesโŒ Disadvantages
No upfront hardware investmentOngoing subscription costs
Pay-as-you-go, easily scalableRequires internet connection
Access from anywhere, real-time collaborationData security/privacy depends on provider
Automatic backupsProvider downtime = your downtime
Shared data centres are more efficient per userVery large overall energy consumption

๐Ÿš€ Emerging Technologies

The 2024 exam listed these. Know one advantage and one disadvantage for each!

โš›๏ธ
Quantum Computing
โœ… Solves problems classical computers can't (drug discovery, cryptography, optimisation)
โŒ Extremely expensive, fragile (needs near absolute zero), would break current encryption
๐Ÿ“ก
Edge Computing
โœ… Processing near the data source โ€” faster response, lower bandwidth costs
โŒ More attack surface (many distributed devices), harder to update/secure
๐Ÿ 
Internet of Things (IoT)
โœ… Everyday objects networked โ€” automation, smart homes, data insights
โŒ Privacy risks, security vulnerabilities, dependence on power/internet
๐Ÿ”’
Biometric Authentication
โœ… Convenient, hard to forge (face/fingerprint/voice)
โŒ Cannot reset if data is leaked, false positives, possible bias in recognition
๐Ÿ”—
Blockchain
โœ… Distributed tamper-evident ledger โ€” trust without intermediaries, transparent
โŒ High energy consumption, errors are irreversible, scalability issues

2024 paper: "Describe one advantage and one disadvantage of quantum computing." Pick any trend above and apply the same structure: name it, advantage with explanation, disadvantage with explanation.

Automation โ€” Benefits & Limits

Examples of automation: robotic process automation (filling forms, sending invoices), industrial robots in factories, self-checkout, automated driving, scheduling/CI pipelines.

โœ… BenefitsโŒ Limitations
Faster, consistent, 24/7 operationHigh upfront cost
Reduces human error in repetitive tasksBrittle โ€” fails if conditions change unexpectedly
Frees humans for higher-value workDisplaces workers, unemployment concerns
Scales easily with demandRequires ongoing maintenance

2025 paper asked about how computing automates processes with a limit โ€” always give a specific example (e.g. self-checkout) and a specific limitation (e.g. customers still need assistance when the machine errors).

๐Ÿ“Š Chapter 5 โ€” Data & Number Systems

Binary, hex, data types, character encoding, cryptography & cybersecurity. Heavy on calculations!

5

๐Ÿ”ข Binary, Decimal & Hexadecimal โ€” Number Systems

Computers use binary (base 2) because transistors have exactly two states: ON (1) and OFF (0). This maps perfectly to physical electrical signals, making circuits simple and reliable.

Binary is like a row of light switches โ€” each is either ON (1) or OFF (0). With 8 switches (1 byte) you can make 256 different patterns (0โ€“255). More switches = more numbers you can represent!

๐Ÿงฎ Interactive Number Converter

Type any number to convert instantly

RESULT
Type in any box above to see all three representations!

Binary โ†’ Decimal: Place Value Method

Every bit position has a value that doubles as you go left. 8-bit place values:

Position2โท2โถ2โต2โด2ยณ2ยฒ2ยน2โฐ
Value1286432168421

Example: 11001001 = 128+64+0+0+8+0+0+1 = 201

Decimal โ†’ Binary: Repeated Division by 2

  1. 1
    Divide the decimal by 2. Write down the remainder (0 or 1).
  2. 2
    Divide the quotient by 2 again. Write down the remainder.
  3. 3
    Repeat until the quotient is 0.
  4. 4
    Read the remainders bottom to top โ€” that's your binary number!

Example: 13 รท 2 = 6 R1 โ†’ 6 รท 2 = 3 R0 โ†’ 3 รท 2 = 1 R1 โ†’ 1 รท 2 = 0 R1 โ†’ Read bottom-up: 1101

Divide by 2 and collect remainders โ€” then read upwards! Like reading a stack of papers from the bottom.

Hexadecimal (Base 16)

Hexadecimal is a base-16 system using digits 0โ€“9 and letters Aโ€“F (where A=10, B=11, C=12, D=13, E=14, F=15). It is used as a compact shorthand for binary โ€” every byte = exactly 2 hex digits.

Hex is like a shorthand language for binary. Writing FF is easier than 11111111. That's why colour codes (#FF5733), memory addresses, and MAC addresses use hex โ€” fewer mistakes, easier to read!

DecimalBinary (nibble)Hex
0โ€“90000โ€“10010โ€“9
101010A
111011B
121100C
131101D
141110E
151111F

After 9 comes A B C D E F = 10 11 12 13 14 15. Mnemonic: "Amazing Binary Converter Delivers Exact Figures!"

Binary โ†” Hexadecimal Conversion

Group binary into nibbles (groups of 4) from the right, then convert each nibble to one hex digit.

Example: 10110101 โ†’ 1011|0101 โ†’ B|5 โ†’ B5โ‚โ‚†

Reverse: each hex digit expands to 4 binary bits. C9 โ†’ 1100 1001

Hex โ†’ Decimal (Exam Calculation!)

Multiply each hex digit by its place value (powers of 16).

Example C9โ‚โ‚†: C = 12, 9 = 9.
(12 ร— 16ยน) + (9 ร— 16โฐ) = 192 + 9 = 201 โœ…

2023 paper asked: convert C9โ‚โ‚† to decimal. DEB 2024 asked: convert binary to hex using nibble grouping. Practice these calculations until they're automatic!

๐ŸŽจ Hex Colour Codes & Download Time Calculations

Hex Colour Codes โ†’ RGB

Colour codes like #0A33F0 have 3 pairs of hex digits: RR GG BB. Convert each pair to decimal to get the RGB values.

Example #0A33F0: Red = 0Aโ‚โ‚† = 10, Green = 33โ‚โ‚† = (3ร—16)+3 = 51, Blue = F0โ‚โ‚† = (15ร—16)+0 = 240

๐ŸŽจ Interactive Hex Colour Explorer

2025 paper: convert #0A33F0 to RGB decimal. Method: split into 3 pairs (0A, 33, F0), convert each pair using the hexโ†’decimal formula. R=10, G=51, B=240.

Download Time Calculation

Download time formula: Time (s) = File size (MB) รท Transfer rate (MB/s). To convert Mbps to MB/s: divide by 8 (8 bits per byte).

Internet speed is measured in megabits per second (Mbps), but file sizes are in megabytes (MB). Since 1 byte = 8 bits, divide speed by 8 to get MB/s. Like converting km/h to m/s โ€” different units, same thing!

โฑ๏ธ Download Time Calculator

Fill in the fields above and click Calculate!

Formula: File size (MB) รท (Speed Mbps รท 8). Remember: divide speed by 8 because there are 8 bits in a byte!

๐Ÿ“‚ Data Types & Continuous vs Discrete Data

Common Data Types

Data TypeDescriptionExamples
IntegerWhole number (positive, negative, or zero)255, -99, 0, 42
Float / RealNumber with a decimal point3.14, -99.99, 1.7
StringText โ€” any sequence of characters"Ciara", "083-1234567", "Hello!"
BooleanTrue or False only โ€” two possible valuesTrue, False
List / ArrayOrdered collection of values[1.5, 1.7], ["red", "blue"]
DateA calendar date or time2024-01-15, 14:30:00

2023 paper: identify the correct data type for: "Ciara" = String; 255 = Integer; 083-1234567 = String (leading 0 and dash); [1.5, 1.7] = List; False = Boolean; -99.99 = Float/Real. Common mistake: phone numbers are Strings because of leading zeros and dashes!

Phone numbers are Strings โ€” never Integers! You can't do maths with a phone number, and 083... has a leading zero which would be lost in Integer form.

Continuous vs Discrete Data

Continuous data can take ANY value within a range โ€” including fractions and decimals. Examples: temperature, height, weight, speed, time.

Continuous = a dial (can be at any position). Temperature can be 20.5, 20.51, 20.512ยฐC โ€” infinite possible values between 20 and 21!

Discrete data can only take specific, separate values โ€” usually whole numbers or categories. Examples: number of students, shoe sizes, number of cars.

Discrete = a light switch (on or off, nothing between). You can have 30 students or 31 students, but never 30.5 students!

๐Ÿ”ค ASCII & Unicode โ€” Character Encoding

Character encoding is a system that assigns a number (binary code) to every character (letter, digit, symbol) so computers can store and transmit text.

FeatureASCIIUnicode (UTF-8/UTF-16)
Year created1963 (revised 1986)1991 (ongoing)
Bits per character7-bit (128 chars) or extended 8-bit (256 chars)Variable: 8โ€“32 bits per character
Number of characters128 (standard) or 256 (extended)140,000+ characters
Languages supportedEnglish/Latin onlyALL world scripts + emoji + maths
Memory useVery compact (1 byte per char)More memory (1โ€“4 bytes per char in UTF-8)
CompatibilityN/AFirst 128 codes = same as ASCII (backwards compatible)

ASCII is a tiny local library โ€” great for English books only. Unicode is the world's biggest library โ€” every book in every language, plus emoji! But a bigger library needs a bigger building (more memory).

ASCII = American โ†’ English only. Unicode = Universal โ†’ every language. Unicode was needed because by the 1980s, different countries had incompatible character sets that couldn't communicate with each other.

2025 paper: "Compare ASCII and Unicode in terms of memory use and compatibility." ASCII = less memory (7/8 bits), English only, not globally compatible. Unicode = more memory, supports all languages, globally compatible, backwards compatible with ASCII.

๐Ÿ” Cryptography & Cybersecurity

Caesar Cipher โ€” Shift Cipher

A Caesar Cipher shifts every letter in the alphabet by a fixed number n. To decode: shift each letter backwards by n, wrapping around using modulo 26.

Decode formula: Decoded position = (letter_position โˆ’ n) mod 26

๐Ÿ” Caesar Cipher Decoder

Enter a message above and click Decode or Encode!

Caesar cipher encode = shift forward n. Decode = shift backward n. Modulo handles the wrap-around (after Z comes A). DEB 2023 used shift n=7. HELLO shifted by 7 = OLSSV.

Pigpen Cipher

The Pigpen cipher uses two key grids โ€” a # grid and an X grid โ€” where each letter's position in the grid becomes its symbol (the shape of the segment it sits in).

To decode: match the shape of each symbol to the matching segment in the key diagram. Pure pattern recognition, no maths!

DEB 2024 asked you to decode a Pigpen message using a given key diagram. Strategy: look at the shape (the lines/corners), find which grid segment has that shape, and read the letter inside.

Cybersecurity Threats & Measures

Ransomware is malware that encrypts the victim's files and demands payment (ransom) to restore access. The 2022 paper used the HSE cyberattack as a case study.

Ransomware is like someone breaking into your house, locking all your belongings in a safe, and demanding money for the combination. Pay and you might (or might not) get your stuff back!

Security MeasureHow it helps
EncryptionMakes data unreadable without the decryption key โ€” even if stolen, data is useless
Multi-factor authentication (MFA)Requires 2+ proofs of identity โ€” password + phone code
VPNCreates an encrypted tunnel for remote workers
FirewallBlocks unauthorised network access
Regular backupsOffline backups allow recovery if data is lost/encrypted
Staff trainingMost breaches start with human error (phishing emails)
Software updates/patchesFixes known security vulnerabilities

DEB 2024: "State 3 methods to protect data in a database." DEB 2023: "State 3 IT security measures for remote working." Good answers: encryption, MFA/strong passwords, VPN, regular backups, firewalls, patch management.

Impact of a Data Breach on Individuals

โš™๏ธ Chapter 6 โ€” Algorithms & Complexity

Bubble, Insertion, Selection, Quicksort, Binary Search & Big O. Sorting appears on EVERY paper!

6

๐Ÿ“ˆ Big O Notation โ€” Algorithm Complexity

Big O notation describes the relationship between the size of the input (N) and the number of steps an algorithm takes. It measures the amount of work โ€” NOT actual speed โ€” and tells you how the algorithm scales as input grows.

Big O is like asking: "If I double the number of students in a class, how much longer does the roll-call take?" O(n) = twice as long. O(nยฒ) = four times as long. O(log n) = barely any longer!

O(1)
Constant
Same steps no matter how big input is. Example: accessing a list by index.
O(log n)
Logarithmic
Halves the problem each step. Example: Binary Search.
O(n)
Linear
Steps grow with input. Example: Linear Search.
O(n log n)
Linearithmic
Good for sorting. Example: Quicksort (average), Mergesort.
O(nยฒ)
Quadratic
Nested loops. Example: Bubble, Insertion, Selection Sort.

O(nยฒ) Explained โ€” What does it mean?

Input size (n)O(nยฒ) operationsMeaning
5~255 ร— 5 = manageable
10~100Doubled input โ†’ 4x the work
100~10,000Starting to get slow
1,000~1,000,000Very slow!

Best โ†’ Worst: O(1) โ†’ O(log n) โ†’ O(n) โ†’ O(n log n) โ†’ O(nยฒ)
"One Lucky ninja never needs nยฒ ninjas!" ๐Ÿฅท

DEB 2024: "Sort these Big O complexities from best to worst." Answer: O(1) โ†’ O(log n) โ†’ O(n) โ†’ O(n log n) โ†’ O(nยฒ). Also know which algorithm gives which: Binary Search = O(log n), Linear Search = O(n), Quicksort avg = O(n log n), Bubble/Insertion/Selection = O(nยฒ).

๐Ÿซง Bubble Sort โ€” O(nยฒ)

Bubble Sort compares adjacent pairs and swaps them if they're in the wrong order. After each full pass, the largest unsorted element "bubbles up" to its correct position at the end.

Like bubbles rising in water โ€” the biggest bubble always floats to the top first. After each pass, one more element is in its correct position at the end, and you never need to look at it again!

  1. 1
    Compare elements at positions [0] and [1]. If arr[0] > arr[1], swap them.
  2. 2
    Move to positions [1] and [2]. Compare and swap if needed.
  3. 3
    Continue to the end of the unsorted portion. After pass 1, the largest element is in its final position.
  4. 4
    Repeat, reducing the unsorted range by 1 each time.
  5. 5
    Optimisation: if a whole pass completes with zero swaps, the list is already sorted โ€” stop early! This gives best case O(n).

Example: 5 passes on [50, 70, 30, 60, 20] โ€” 2024 Exam!

PassList after passElement placed
Start[50, 70, 30, 60, 20]โ€”
Pass 1[50, 30, 60, 20, 70]70 โ†’ end โœ…
Pass 2[30, 50, 20, 60, 70]60 โ†’ position 4 โœ…
Pass 3[30, 20, 50, 60, 70]50 โ†’ position 3 โœ…
Pass 4[20, 30, 50, 60, 70]30 โ†’ position 2 โœ…
Pass 5[20, 30, 50, 60, 70]Sorted! โœ…

2024 paper asked you to show 5 passes of bubble sort on [50, 70, 30, 60, 20]. Examcraft 2023 asked you to perform it on [9, 4, 1, 8, 6]. ALWAYS show each pass as a row and highlight what moved.

Time ComplexityDetails
Best caseO(n) โ€” already sorted list with early-exit flag
Average/Worst caseO(nยฒ) โ€” nested loops, many comparisons and swaps

๐Ÿ“Œ Insertion Sort โ€” O(nยฒ)

Insertion Sort builds a sorted list one element at a time. Take the next unsorted element and insert it into its correct position in the already-sorted portion by comparing and shifting elements rightward.

Like sorting playing cards in your hand โ€” you pick up a new card and slide it left into the right position among the cards you're already holding. Each new card finds its place!

  1. 1
    Start with the element at index 1 (element at index 0 is trivially "sorted").
  2. 2
    Compare this element (key) with the element to its left.
  3. 3
    If the left element is bigger, shift it right one position.
  4. 4
    Keep comparing leftwards, shifting larger elements right, until the correct position is found.
  5. 5
    Insert the key into the gap. Move to the next unsorted element.

Example: Bookshelf [7, 2, 4, 1, 5] โ€” 2022 Exam Style!

PassKeyActionList after
122 < 7 โ†’ shift 7 right, insert 2[2, 7, 4, 1, 5]
244 < 7 โ†’ shift 7; 4 > 2 โ†’ insert[2, 4, 7, 1, 5]
311 < 7,4,2 โ†’ shift all; insert 1[1, 2, 4, 7, 5]
455 < 7 โ†’ shift 7; 5 > 4 โ†’ insert[1, 2, 4, 5, 7]

๐Ÿ“Œ Insertion = "Insert each card into its correct place in the hand". Best case = O(n) when already sorted (no shifts needed). Worst case = O(nยฒ) when reverse sorted (maximum shifts).

Time ComplexityDetails
Best caseO(n) โ€” already sorted, just one comparison per element
Average/Worst caseO(nยฒ) โ€” reverse sorted, maximum shifts each pass

๐ŸŽฏ Selection Sort โ€” O(nยฒ)

Selection Sort repeatedly finds the minimum value in the unsorted portion and places it at the start of that portion (by swapping). After each pass, one more element is in its final position.

Like a teacher picking the shortest student first and placing them at the front, then picking the next shortest, and so on. You're always selecting the smallest remaining item!

  1. 1
    Find the minimum value in the entire unsorted section (indices 0 to n-1).
  2. 2
    Swap it with the element at the current start position (index 0).
  3. 3
    Move the sorted boundary one position right. Now find the min in indices 1 to n-1.
  4. 4
    Repeat until fully sorted.

Example: [64, 25, 12, 22, 11]

PassMin foundSwapList after
111 (index 4)11 โ†” 64[11, 25, 12, 22, 64]
212 (index 2)12 โ†” 25[11, 12, 25, 22, 64]
322 (index 3)22 โ†” 25[11, 12, 22, 25, 64]
425 (index 3)already there[11, 12, 22, 25, 64]

๐ŸŽฏ "Selection = always Selecting the Smallest". Unlike bubble sort which moves things around a lot, selection sort makes exactly n-1 swaps total.

Always O(nยฒ) regardless of input order โ€” no best-case optimisation like bubble/insertion. 2022 paper gave a two-list version โ€” know both in-place (swap) and two-list versions.

โšก Quicksort โ€” O(n log n) average, O(nยฒ) worst

Quicksort is a divide-and-conquer algorithm. Choose a pivot element; partition the list into elements โ‰ค pivot (left) and elements > pivot (right); then recursively sort each partition.

Like organising a pile of books by price. Pick one book as a "pivot". Put all cheaper books on the left, all more expensive on the right. Now do the same thing separately on the left pile and right pile. Keep dividing until everything is sorted!

Interactive Quicksort Partitioning

Press "Step" to partition around the pivot (shown in pink).

Pivot โ‰ค pivot > pivot

Tracing Quicksort โ€” 2023 Exam: Pivot = 60 on [60,30,80,40,10,50,20,70,90]

  1. 1
    Choose pivot = 60.
  2. 2
    Left partition (โ‰ค 60): [30, 40, 10, 50, 20]
  3. 3
    Right partition (> 60): [80, 70, 90]
  4. 4
    Result: [30,40,10,50,20] | 60 | [80,70,90]
  5. 5
    Recursively sort each partition until all single elements remain.

Why is 90 a bad pivot choice? โ€” 2023 Exam!

If pivot = 90 (the maximum), left partition = all 8 other elements, right partition = empty. No meaningful split occurs โ€” this degrades to O(nยฒ) because we do n comparisons, then n-1, then n-2... same as Bubble Sort. Good pivot strategies: pick the median of first/middle/last elements, or a random element.

2025 Exam: Pivot = 13 on [29,10,14,37,13]

StepActionResult
PivotChoose 13 as pivotpivot = 13
Left (โ‰ค13)10, 13 โ‰ค 13[10] | 13
Right (>13)29, 14, 37 > 13[29, 14, 37]
Next stepRecursively sort [10] (already sorted) and [29,14,37]Continue...
Time ComplexityDetails
Best caseO(n log n) โ€” pivot always splits into two equal halves
Average caseO(n log n) โ€” with random or median pivot selection
Worst caseO(nยฒ) โ€” when pivot is always the largest/smallest element

โšก Quicksort = Quick in practice (O(n log n) average), but can be Slow with a bad pivot (O(nยฒ)). Always choose a good pivot!

๐Ÿ” Binary Search โ€” O(log n)

Binary Search finds a target in a sorted list by repeatedly halving the search space. Compare the target to the middle element: if equal = found; if target is smaller = search left half; if larger = search right half.

Like finding a name in a phone book โ€” open to the middle, decide which half has the name, repeat. You never look at the wrong half again! Much faster than reading every page!

  1. 1
    Set low = 0, high = len(list) - 1.
  2. 2
    Calculate mid = (low + high) // 2.
  3. 3
    If list[mid] == target โ†’ return mid (found!).
  4. 4
    If target < list[mid] โ†’ set high = mid - 1 (search left half).
  5. 5
    If target > list[mid] โ†’ set low = mid + 1 (search right half).
  6. 6
    Repeat until found or low > high (not in list).

Tracing Binary Search โ€” Example: find 37 in [2, 7, 14, 22, 37, 51, 68]

Steplowhighmidlist[mid]Action
10632237 > 22 โ†’ low = 4
24655137 < 51 โ†’ high = 4
344437โœ… Found at index 4!

๐Ÿ” Binary Search = always halves the list. List of 1,000 items needs at most 10 comparisons (because 2ยนโฐ = 1,024). That's why it's O(log n)!

2023 paper: trace a Python binary search function โ€” identify the iteration (while loop), explain what happens when target not found (return len(L) instead of -1). Know this quirk!

Sorting a Dataset โ€” Advantage & Disadvantage

โœ… Advantage of sortingโŒ Disadvantage of sorting
Enables fast binary search (O(log n) vs O(n))Sorting itself takes time โ€” O(n log n) or worse
Easier to find duplicates and generate reportsIf data changes frequently, must re-sort often (costly)

๐Ÿ“‹ Algorithm Comparison โ€” The Complete Summary

AlgorithmTypeBestAverageWorstSorted input required?
Linear SearchSearchO(1)O(n)O(n)โŒ No
Binary SearchSearchO(1)O(log n)O(log n)โœ… YES
Bubble SortSortO(n)*O(nยฒ)O(nยฒ)N/A โ€” it sorts
Insertion SortSortO(n)*O(nยฒ)O(nยฒ)N/A โ€” it sorts
Selection SortSortO(nยฒ)O(nยฒ)O(nยฒ)N/A โ€” it sorts
QuicksortSortO(n log n)O(n log n)O(nยฒ)N/A โ€” it sorts

* O(n) best case requires early-exit flag on already-sorted list

The most common exam questions: (1) Perform an algorithm step by step. (2) State the Big O complexity. (3) Compare two algorithms. (4) Explain why Quicksort can degrade to O(nยฒ). (5) State one improvement to Bubble Sort (early-exit flag).

๐Ÿƒ Flashcards

Click a card to flip it. Filter by chapter to focus your revision.

?
Chapter 4

Loading...

Tap to reveal โ†ป

1 / 1

๐ŸŽฏ Quick Quiz

Test your knowledge across all three chapters. Past-paper style questions!